<!--
 * @Description:
 * @Autor: luojie
 * @Date: 2021-08-07 20:56:24
 * @LastEditors: luojie
 * @LastEditTime: 2021-08-09 10:33:53
-->
<template>
	<view>
    <view class="content">
      <scroll-view class="record-box" scroll-y="true" ref="recordList" lower-threshold="50" @scrolltolower="pageHandler">
        <view class="record-main">
          <view class="record" v-for="(item,index) in recordList" :key="index" @click="fileHandler(item)">
            <view class="record-item">
              <view class="record-item-title">【{{item.myFileName}}】{{item.name}}</view>
              <!-- <view class="record-item-desc">
                <text class="text-item">类型：{{item.typeName}}</text>
                <text class="text-item">发布时间：{{dayjs(item.moditime).format('YYYY-MM-DD')}}</text>
              </view> -->
            </view>
            <!-- <view class="record-icon">
              <view>
                <icon type="info" size="26"/>
              </view>
              <text>预览</text>
            </view> -->
          </view>
          <view class="no-more">{{ dataText }}</view>
        </view>
      </scroll-view>
    </view>
	</view>
</template>

<script>

import { getTrainingDetail,getData } from "@/api";
import dayjs from 'dayjs'
import { downloadFile } from "@/request/request";

export default {
  data() {
    return {
      dayjs,
      dataType: '1',
      recordList:[],
      total: 0,
      pageNum: 1,
      size: 10,
      finished: false,
      dataText: '暂无数据',
      currentTab:0,
      dataList: [],
      typeId:'',
      rootPath: wx.env.USER_DATA_PATH,
    }
  },
  onLoad(e) {
    uni.setNavigationBarTitle({ title: e.title })
    this.typeId = e.typeId;
    uni.showLoading({
      mask: true
    });
    this.getDataList();
  },
  methods: {
    pageHandler() {
      if (!this.finished) {
        this.pageNum ++;
        this.getDataList();
      }
    },
    getDataList() {
      console.log('pageNum=', this.pageNum);
      const data = {
        pageNum: this.pageNum,
        pageSize: this.size,
        typeId: this.typeId
      };
      getData('getTrainingList','get',data).then((res) => {
        console.log('res===', res);
        if(res.records) {
          res.records.forEach(item=>{
            if(item.fileList.length){
              item.myFileName = '文件'
            }
            if(item.linkList.length && item.linkList[0].linkUrl){
              let suffix = item.linkList[0].linkUrl.substr(item.linkList[0].linkUrl.length-4)
              if(suffix == '.mp4' || suffix == '.MP4'){
                item.myFileName = '视频'
              }
            }
          })
          this.recordList = [...this.recordList, ...res.records];
          this.total = res.total;
          if(this.recordList.length === this.total) {
            this.finished = true;
          }
          if (this.total) {
            this.dataText = this.finished ? '没有更多数据' : '加载更多';
          }
        }
        uni.hideLoading();
      });
    },
    fileHandler(row) {
      uni.showLoading({
        mask: true
      });
      let id = row.policyId || row.trainingId
      getTrainingDetail(id).then(res => {
        if (res) {
          uni.hideLoading();
          this.detail = res;
          let file = this.fileList = res.fileList || [];
          let linkList = res.linkList || [];
          this.linkList = linkList = linkList.filter(rs=>{
            let suffix = rs.linkUrl.substr(rs.linkUrl.length-4)
            return suffix == '.mp4' || suffix == '.MP4'
          })
          if (file[0]) {
            let filePath = `${this.rootPath}/${file[0].fileName}`;
            const _this = this;
            this.downloadFile(file[0]);
          } else if(linkList[0] && linkList[0].linkUrl){
            uni.navigateTo({
              url: `/packageAlpha/pages/workHelp/detail?link=${linkList[0].linkUrl}`,
            })
          } else {
            uni.showToast({
              title: '暂无文件',
              icon: 'none'
            })
          }
        }
      })
    },
    // 文件流下载
    downloadFile(row) {
      let filePath = `${this.rootPath}/${row.fileName}`;
      console.log(filePath)
      const _this = this;
      uni.showLoading({
        title: '正在打开文件……',
        mask: true
      });
      downloadFile({ url: '/files/book-download?fileId=' + row.fileId }).then(data => {
        const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
        fs.writeFile({ // 写文件
          filePath,
          data: data,
          encoding: "binary", //二进制流文件必须是 binary
          success(res){
            console.log('write success')
            _this.previewFile(filePath);
          },
          fail(err) {
            uni.showToast({
              title: '文件执行异常',
              icon: 'none'
            })
          },
          complete() {
            uni.hideLoading();
          }
        });
      }).catch(() => {
        uni.hideLoading();
        uni.showToast({
          title: '未找到相关文件',
          icon: 'none'
        })
      })
    },
    // 文件预览
    previewFile(filePath) {
      let imgType = ['.png', '.jpg', '.jpeg'], isImage = false;
      imgType.forEach(t => {
        if (filePath.indexOf(t) != -1) isImage = true;
      })
      uni.showLoading({
        title: '正在打开文件……',
        mask: true
      });
      if (isImage) {
        // 图片预览
        wx.previewImage({
          urls: [filePath],
          fail() {
            uni.showToast({
              title: '打开图片失败',
              icon: 'none'
            })
          },
          complete() {
            uni.hideLoading();
          }
        })
      } else {
        // 文件预览
        wx.openDocument({
          filePath,
          fail() {
            uni.showToast({
              title: '打开文档失败',
              icon: 'none'
            })
          },
          complete() {
            uni.hideLoading();
          }
        })
      }
    },
    goDetail(row) {
      uni.navigateTo({
        url: `/packageAlpha/pages/workHelp/detail?id=${row.policyId || row.trainingId}&dataType=${this.dataType}`,
      })
    }
  }
}
</script>

<style lang="scss" scoped>
	.content{
		height: 100vh;
    display: flex;
    flex-direction: column;
	}
	.filter-btn{
    display: flex;
		flex-wrap:wrap;
    background-color: #fff;
    padding: 0 51rpx;
    padding-top: 34rpx;
  	justify-content:center;
    font-size: 30rpx;
		&-item{
			flex-basis: 126rpx;
			padding-bottom: 20rpx;
			text-align: center;
      white-space: nowrap;
      margin: 0 40rpx
		}
		&-active{
      color: #2C9AF1;
      border-bottom:3px solid #2C9AF1;
    }
	}
  .record-box {
    flex: 1;
    background-color: #f9f9f9;
    overflow-y: scroll;
  }
	.record-main{
		padding:30rpx 32rpx;
		box-sizing: border-box;
    .record{
      width: 100%;
      box-sizing: border-box;
      background-color: #fff;
      padding:26rpx 32rpx;
      border-radius: 10rpx;
      box-shadow: 0px 0px 10px rgba(229, 229, 229, 1);
      margin-bottom: 30rpx;
      display: flex;
      align-items: center;
      font-size: 30rpx;
      &-item{
        flex: 1;
        &-title{
          color: #333;
          font-size: 34rpx;
          line-height: 46rpx;
          // margin-bottom: 20rpx;
        }
        &-desc{
          color: #999;
          font-size: 30rpx;
          line-height: 40rpx;
        }
        &-status{
          color: #66DD55;
          padding: 9rpx 31rpx;
          margin-left: 32rpx;
          border: 1px solid #66DD55;
        }
        &-error{
          color: #F15B53;
          border: 1px solid #F15B53;
        }
      }
      .text-item {
        margin-right: 40rpx;
        &:last-child {
          margin-right: none;
        }
      }
    }
    .record-icon {
      text-align: center;
    }
    .no-more{
      color: #999999;
      font-size: 30rpx;
      margin: 20rpx 0;
      text-align: center;
      height: 80rpx;
    }
	}
</style>>
